import UIKit

class Button: UIViewController, UITextFieldDelegate {


//    //MARK: -UIButton实例

    // 基础按钮
        private var basicButton: UIButton!

        // 圆角按钮
        private var roundedButton: UIButton!

        // 带图标的按钮
        private var iconButton: UIButton!

        // 渐变按钮
        private var gradientButton: UIButton!

        // 禁用状态按钮
        private var disabledButton: UIButton!

        // 按钮点击计数标签
        private var countLabel: UILabel!
        private var tapCount = 0

        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = .systemBackground
            setupUI()
        }

        private func setupUI() {
            let margin: CGFloat = 20
            let yOffset: CGFloat = 100
            let width = view.bounds.width - (margin * 2)
            let buttonHeight: CGFloat = 50

            // 1. 基础按钮
            basicButton = createButton(
                frame: CGRect(x: margin, y: yOffset, width: width, height: buttonHeight),
                title: "基础按钮"
            )
            if #available(iOS 15.0, *) {
                var config = UIButton.Configuration.filled()
                config.baseBackgroundColor = .systemBlue
                config.baseForegroundColor = .white
                config.title = "基础按钮"
                basicButton.configuration = config
            } else {
                basicButton.backgroundColor = .systemBlue
                basicButton.tintColor = .white
            }
            view.addSubview(basicButton)

            // 2. 圆角按钮
            roundedButton = createButton(
                frame: CGRect(x: margin, y: yOffset + 70, width: width, height: buttonHeight),
                title: "圆角按钮"
            )
            if #available(iOS 15.0, *) {
                var config = UIButton.Configuration.filled()
                config.baseBackgroundColor = .systemGreen
                config.baseForegroundColor = .white
                config.cornerStyle = .capsule // iOS 15+ 圆角样式
                config.title = "圆角按钮"
                roundedButton.configuration = config
            } else {
                roundedButton.backgroundColor = .systemGreen
                roundedButton.tintColor = .white
                roundedButton.layer.cornerRadius = buttonHeight / 2
            }
            view.addSubview(roundedButton)

            // 3. 带图标的按钮
            iconButton = createButton(
                frame: CGRect(x: margin, y: yOffset + 140, width: width, height: buttonHeight),
                title: "带图标按钮"
            )
            if #available(iOS 15.0, *) {
                var config = UIButton.Configuration.filled()
                config.baseBackgroundColor = .systemOrange
                config.baseForegroundColor = .white
                config.image = UIImage(systemName: "heart.fill")
                config.imagePadding = 10 // 图像和文本间距
                config.titlePadding = 10
                config.imagePlacement = .leading // 图像位置
                config.title = "带图标按钮"
                iconButton.configuration = config
            } else {
                iconButton.backgroundColor = .systemOrange
                iconButton.tintColor = .white
                //把图标的渲染模式设为alwaysTemplate，这意味着图标会以模板的形式呈现，它的颜色会由按钮当前的tintColor来决定，而不是图标自身原本的颜色。
                let image = UIImage(systemName: "heart.fill")?.withRenderingMode(.alwaysTemplate)
                iconButton.setImage(image, for: .normal)
                iconButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
                iconButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
            }
            view.addSubview(iconButton)

            // 4. 渐变按钮
            gradientButton = createButton(
                frame: CGRect(x: margin, y: yOffset + 210, width: width, height: buttonHeight),
                title: "渐变按钮"
            )
            gradientButton.tintColor = .white

            // 添加渐变背景
            let gradientLayer = CAGradientLayer()
            //这行代码将 CAGradientLayer 类型的 gradientLayer 的大小设置为和 gradientButton 按钮的大小一样。这里的 bounds 属性代表的是按钮自身的坐标系统内的区域范围。
            gradientLayer.frame = gradientButton.bounds
            //此代码为渐变图层 gradientLayer 指定了渐变颜色。具体来说，渐变是从系统预设的紫色（systemPurple）过渡到系统预设的粉色（systemPink）。需要注意的是，这里使用的是 CGColor 类型，所以要通过.cgColor将 UIColor 转换为 CGColor。
            gradientLayer.colors = [UIColor.systemPurple.cgColor, UIColor.systemPink.cgColor]
            //设置渐变图层（CAGradientLayer）的渐变方向，通过修改 startPoint（起点）和 endPoint（终点）来控制颜色过渡的方向和范围。
            gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
            gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)

            if #available(iOS 15.0, *) {
                gradientLayer.cornerRadius = 8
                gradientButton.layer.insertSublayer(gradientLayer, at: 0)

                // 确保按钮内容显示在渐变层上方
                gradientButton.layer.masksToBounds = true
                gradientButton.layer.cornerRadius = 8

                // 使用 plain 配置避免背景覆盖渐变
                var config = UIButton.Configuration.plain()
                config.title = "渐变按钮"
                config.baseForegroundColor = .white
                gradientButton.configuration = config
            } else {
                gradientLayer.cornerRadius = 8
                gradientButton.layer.insertSublayer(gradientLayer, at: 0)
            }
            view.addSubview(gradientButton)

            // 5. 禁用状态按钮
            disabledButton = createButton(
                frame: CGRect(x: margin, y: yOffset + 280, width: width, height: buttonHeight),
                title: "禁用按钮"
            )
            if #available(iOS 15.0, *) {
                var config = UIButton.Configuration.filled()
                config.baseBackgroundColor = .systemGray
                config.baseForegroundColor = .white
                config.title = "禁用按钮"
                disabledButton.configuration = config
            } else {
                disabledButton.backgroundColor = .systemGray
                disabledButton.tintColor = .white
            }
            disabledButton.isEnabled = false // 禁用按钮
            view.addSubview(disabledButton)
//
            // 计数标签
            countLabel = UILabel(frame: CGRect(x: margin, y: yOffset + 350, width: width, height: 40))
            countLabel.textAlignment = .center
            countLabel.font = UIFont.systemFont(ofSize: 18, weight: .medium)
            countLabel.text = "点击次数: 0"
            view.addSubview(countLabel)
        }

        private func createButton(frame: CGRect, title: String) -> UIButton {
            let button = UIButton(type: .system)
            button.frame = frame
            button.setTitle(title, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
            button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
            return button
        }

        @objc private func buttonTapped(_ sender: UIButton) {
            tapCount += 1
            countLabel.text = "点击次数: \(tapCount)"

            // 添加按钮点击动画
            UIView.animate(withDuration: 0.2) {
                sender.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
            } completion: { _ in
                UIView.animate(withDuration: 0.2) {
                    sender.transform = .identity
                }
            }

            // 根据不同按钮显示不同提示
            let buttonTitle = sender.title(for: .normal) ?? "按钮"
            let alert = UIAlertController(title: "按钮点击", message: "你点击了 \(buttonTitle)", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "确定", style: .default))
            present(alert, animated: true)
        }

        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            // 更新渐变层的 frame
            //gradientButton.layer.sublayers?.first as? CAGradientLayer借助可选链，代码先尝试获取按钮图层的子图层数组（也就是sublayers）。要是这个数组存在，就取出它的第一个子图层，接着尝试把这个子图层转换为CAGradientLayer类型。
            if let gradientLayer = gradientButton.layer.sublayers?.first as? CAGradientLayer {
                //将渐变图层的大小调整为和按钮的大小一致。这里的bounds属性代表的是按钮自身坐标系统内的区域范围，这样做能保证渐变效果可以完全覆盖按钮。
                gradientLayer.frame = gradientButton.bounds
            }
        }
    
}
